package flex.cc.single.quartz;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.http.HttpStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;

import flex.cc.common.utils.CommonUtils;
import flex.cc.common.utils.HttpClientUtil;
import flex.cc.single.dto.entity.VerifyTaskEntity;
import flex.cc.single.dto.entity.VerifyTaskRecordEntity;
import flex.cc.single.service.VerifyTaskRecordService;
import flex.cc.single.service.VerifyTaskService;
import flex.cc.util.DateUtil;

/**
 * 
 * @author WANGCONG
 * 2022年4月1日下午14:39:28
 * @desc 定时任务类：单项卡券核销通知失败信息定时补推上游
 */
@Component
@EnableScheduling
public class QuartzVerifyTask {

	private static final Logger logger = LoggerFactory.getLogger(QuartzVerifyTask.class);
	@Resource
	private VerifyTaskService taskService;
	@Resource
	private VerifyTaskRecordService taskRecordService;
	
//	@Scheduled(cron = "*/10 * * * * ?") //10秒执行一次
//	@Scheduled(cron = "0 30 10 * * ?")    //每天十点半
//	@Scheduled(cron = "0 0 0 * * ?")    //每天凌晨零时执行
	@SuppressWarnings("serial")
	@Scheduled(cron = "0 0 1 * * ?")    //每天凌晨1时执行
    public void writeOffTask(){
		logger.info("QuartzVerifyTask定时核销补推开始:time=" + DateUtil.DateToString(new Date()));
		Map<String, Object> taskParams = new HashMap<String, Object>();
		taskParams.put("status", "1"); //核销结果：0-成功、1-失败
		List<VerifyTaskEntity> taskList = taskService.getListByParams(taskParams); //查询未核销通过的历史数据
		for(int i=0; i<taskList.size(); i++){
			VerifyTaskEntity taskVo = taskList.get(i);
			String cardType = ""; //卡券归属类型：1-服务包到店、2-服务包代驾、3-单项到店、4-单项代驾、5-健康护理
			String resultJson = ""; //响应结果报文
			String resultCode = "success";  //响应码code
			String resultMsg = "核销成功";  //响应结果描述
			try {
				cardType = taskVo.getCardType();
				if(!"3".equals(cardType) && !"4".equals(cardType)){
					resultJson = CommonUtils.storePost(taskVo.getWriteOffUrl(), taskVo.getRequestBody());
				}else{
					resultJson = HttpClientUtil.sendHttpPostText(taskVo.getWriteOffUrl(), taskVo.getRequestBody(), 
							new HashMap<String, String>(){{put("Content-Type", "text/plain;charset=UTF-8");
			        }});
				}
				logger.info("定时任务核销补推响应报文==>> CouponNum:{}, Result:{}", taskVo.getCouponNum(), resultJson);
				/**
				 * 不同的类型，核销响应报文不同===>
				 * 服务包到店类、代驾类：
				 *  {"result":{"errMsg":"第三方卡券统一核销接口调用成功！","status":"success"},"resultCode":200,"message":"OK"}
				 * 健康护理类：
				 *  同服务包到店类、代驾类
				 * 单项到店类、代驾类：
				 *  {"resCode": "SUCCESS","resMsg": ""}
				 */
				if (resultJson != null) {
					JSONObject json = JSONObject.parseObject(resultJson);
					switch (cardType) {
						case "1": case "2": //服务包到店、代驾
							int code = Integer.valueOf(json.get("resultCode").toString());
							if(HttpStatus.SC_OK == code){ //调用成功
								JSONObject results = (JSONObject)json.get("result");
								String status = results.get("status").toString();
								if("success".equals(status)){
									//更新当前记录的核销状态：失败改为成功、更新时间，插入一条历史记录
								}else{
									resultCode = "error";
									resultMsg = results.get("errMsg").toString();
									//插入一条核销补推历史记录
								}
							}else{
								resultCode = "error";
								resultMsg = json.get("message").toString();
								//插入一条核销补推历史记录
							}
							break;
							
						case "3": case "4": //单项到店、代驾
							String resCode = (String) json.get("resultCode"); //响应码
							if("1".equals(resCode)){
								//更新当前记录的核销状态：失败改为成功、更新时间，插入一条历史记录
							}else{
								resultCode = "error";
								resultMsg = (String) json.get("resultMessage"); //结果描述
							}
							break;
						case "5": //健康护理
							int apiCode = Integer.valueOf(json.get("resultCode").toString());
							if(HttpStatus.SC_OK == apiCode){ //调用成功
								JSONObject results = (JSONObject)json.get("result");
								String status = results.get("status").toString();
								if("success".equals(status)){
									//更新当前记录的核销状态：失败改为成功、更新时间，插入一条历史记录
								}else{
									resultCode = "error";
									resultMsg = results.get("errMsg").toString();
									//插入一条核销补推历史记录
								}
							}else{
								resultCode = "error";
								resultMsg = json.get("message").toString();
								//插入一条核销补推历史记录
							}
							break;
					
					}
				}else{
					resultCode = "error";
					resultMsg = "核销失败，响应报文为空";
					//插入一条核销补推历史记录
				}
			} catch (Exception e) {
				resultCode = "error";
				resultMsg = "核销失败，响应报文处理异常";
			}
			logger.info("定时任务核销补推处理结果==>> CouponNum:{}, Code:{}, Result:{}", taskVo.getCouponNum(), resultCode, resultMsg);
			try {
				Date date = new Date();
				if("success".equals(resultCode)){
					taskVo.setStatus(0); //核销结果：0-成功、1-失败
					taskVo.setUpdateTime(date);
					taskService.update(taskVo);
				}
				VerifyTaskRecordEntity recordEntity = new VerifyTaskRecordEntity();
				BeanUtils.copyProperties(recordEntity , taskVo);
				recordEntity.setId(null);
				recordEntity.setResponseBody(resultJson);
				recordEntity.setCreateTime(date);
				taskRecordService.insert(recordEntity);
			} catch (Exception e) {
				logger.info("---QuartzVerifyTask保存异常了---");
			}
		}
		logger.info("QuartzVerifyTask定时核销补推结束:time=" + DateUtil.DateToString(new Date()));
		
	}
	
}
